import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:go_router/go_router.dart';
import 'package:leader_doctor_flutter/common/data/app.dart';
import 'package:leader_doctor_flutter/common/http/api.dart';
import 'package:leader_doctor_flutter/common/http/http_client.dart';
import 'package:leader_doctor_flutter/common/utils/image_utils.dart';
import 'package:leader_doctor_flutter/common/widget/comm_widget.dart';
import 'package:leader_doctor_flutter/model/prescription.dart';
import 'package:leader_doctor_flutter/styles/colors.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

import '../../../plugins/plugins_messages.g.dart';
import '../../../router/router.dart';
import '../model/icd.dart';

/// @Author lixiaobin
/// @Date 2024/9/25
/// @Description 疾病分类
class IllnessClassifyPage extends StatefulWidget {
  const IllnessClassifyPage({super.key});

  @override
  State<IllnessClassifyPage> createState() => _IllnessClassifyPageState();
}

class _IllnessClassifyPageState extends State<IllnessClassifyPage> {
  final _textController = TextEditingController();
  final _icdList = <ICDModel>[];
  var _isPrint = 0;
  var _pageNo = 1;
  final _pageSize = 20;
  final _refreshController = RefreshController(initialRefresh: false);

  void _onRefresh() async {
    _pageNo = 1;
    _getPrescriptionList();
  }

  void _onLoading() async {
    _pageNo++;
    _getPrescriptionList();
  }

  @override
  void initState() {
    super.initState();
    _onRefresh();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: CommWidget.getCommAppbar(context),
        body: Container(
            color: ColorRes.white,
            child: Column(
              children: [
                _buildSearchView(),
                _buildListView(),
              ],
            )));
  }

  /// 搜索
  Widget _buildSearchView() {
    return Container(
        color: ColorRes.white,
        child: Container(
          height: 40.w,
          padding: EdgeInsets.only(left: 8.w, right: 8.w),
          margin: EdgeInsets.only(left: 16.w, right: 16.w, top: 8.w, bottom: 8.w),
          decoration: BoxDecoration(color: ColorRes.colorf5f5f5, borderRadius: BorderRadius.circular(6.w)),
          child: Row(
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              ImageLoader.loadAsset('icon_search.png', 18.w),
              SizedBox(width: 8.w),
              Expanded(
                  child: TextField(
                      controller: _textController,
                      textInputAction: TextInputAction.search,
                      onSubmitted: (str) => _onRefresh(),
                      onChanged: (str) => _onRefresh(),
                      style: TextStyle(color: ColorRes.color333333, fontSize: 14.sp),
                      decoration: const InputDecoration(
                          hintText: '请输入关键字',
                          hintStyle: TextStyle(color: ColorRes.colorc3c3c3),
                          border: InputBorder.none)))
            ],
          ),
        ));
  }

  Widget _buildListView() {
    return Expanded(child: _buildSmartRefresher());
  }

  /// 刷新组件
  Widget _buildSmartRefresher() {
    return SmartRefresher(
        controller: _refreshController,
        enablePullDown: true,
        enablePullUp: true,
        onRefresh: _onRefresh,
        onLoading: _onLoading,
        child: _icdList.isEmpty
            ? CommWidget.buildEmptyView(tipStr: '暂无疾病分类数据')
            : ListView.separated(
                shrinkWrap: true,
                itemBuilder: (c, i) => _buildItem(c, i),
                separatorBuilder: (c, i) => _buildSeparator(c, i),
                itemCount: _icdList.length));
  }

  /// 列表item
  Widget _buildItem(BuildContext c, int i) {
    var model = _icdList[i];
    return GestureDetector(
        behavior: HitTestBehavior.opaque,
        onTap: () {
          NativeInterface().icdSelect(jsonEncode(model));
          Future.delayed(const Duration(milliseconds: 300), () => CommWidget.pop(context));
        },
        child: Container(
            margin: EdgeInsets.only(left: 16.w, right: 16.w),
            alignment: Alignment.centerLeft,
            height: 50.w,
            child: Text(
              model.icdName ?? '',
              style: TextStyle(color: ColorRes.color333333, fontSize: 15.sp),
            )));
  }

  /// 分割线
  Widget _buildSeparator(BuildContext c, int i) {
    return Container(
      height: 1.w,
      color: ColorRes.colorf1f6fe,
    );
  }

  /// 获取开单列表
  _getPrescriptionList() async {
    var urlParams = {
      'name': _textController.text,
      'pageIndex': _pageNo,
      'pageSize': _pageSize,
    };
    var response = await HttpClient.get(HttpRequest(Api.icdList, urlParams: urlParams));
    var serviceResult =
        ServiceResult<List<ICDModel>>.list(response, (map) => (map ?? []).map((e) => ICDModel.fromJson(e)).toList());

    if (serviceResult.success) {
      var list = serviceResult.responseBody;
      if (_pageNo == 1) {
        _icdList.clear();
      }
      _icdList.addAll(list ?? []);
    }

    _refreshController.refreshCompleted();
    _refreshController.loadComplete();
    setState(() {});
  }
}
